<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="accountSelected" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="handlerSyncAccountFans">
        同步菜单
      </el-button>
    </div>
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate('')">{{ $t('table.add') }}
      </el-button>
    </div>
    <tree-table :data="data" :columns="columns" border v-loading="listLoading">
      <!--<el-table-column :label="tempDesc.wxAccountName">-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.wxAccountName }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column :label="tempDesc.menuName">
        <template slot-scope="scope">
          <span>{{ scope.row.menuName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.menuType" :formatter="formatMenuType">
      </el-table-column>
      <el-table-column :label="tempDesc.menuLevel" :formatter="formatMenuLevel">
      </el-table-column>
      <el-table-column :label="tempDesc.menuSort">
        <template slot-scope="scope">
          <span>{{ scope.row.menuSort }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.tplName">
        <template slot-scope="scope">
          <span>{{ scope.row.tplName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.menuUrl" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.menuUrl }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.miniprogramAppid" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.miniprogramAppid }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.miniprogramPagepath" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.miniprogramPagepath }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.createTime" width="160px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.updateTime" width="160px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleCreate(scope.row)" v-show="scope.row.menuLevel == '1'">{{ $t('table.add') }}</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </tree-table>

    <el-dialog :title="temp.menuLevel ==='1' ? textMap[dialogStatus] + '一级菜单' : textMap[dialogStatus] + '二级菜单'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px"
               style="width: 400px; margin-left:50px;">
        <el-form-item :label="tempDesc.wxAccountId" prop="wxAccountId">
          <el-select v-model="temp.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 280px;" :disabled="(temp.menuLevel ==='1' && dialogStatus !='create') || temp.menuLevel ==='2'">
            <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.menuName" prop="menuName">
          <el-input v-model="temp.menuName" :placeholder="'请输入' + tempDesc.menuName"/>
        </el-form-item>
        <el-form-item :label="tempDesc.menuType" prop="menuType">
          <el-select v-model="temp.menuType" class="filter-item" :placeholder="'请选择' + tempDesc.menuType" style="width: 280px;" clearable @change="onMenuTypeChange">
            <el-option v-for="item in menuTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.menuLevel" prop="menuLevel">
          <el-select v-model="temp.menuLevel" class="filter-item" :placeholder="'请选择' + tempDesc.menuLevel" style="width: 280px;" disabled>
            <el-option v-for="item in menuLevelOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.menuSort" prop="menuSort">
          <el-input type="number" v-model="temp.menuSort" :placeholder="'请输入' + tempDesc.menuSort"/>
        </el-form-item>
        <!--<el-form-item :label="tempDesc.tplId" prop="tplId">-->
          <!--<el-select v-model="temp.tplId" class="filter-item" placeholder="请选择模板" style="width: 280px;" :disabled="!(temp.menuType == '1' || temp.menuType == '2')" clearable>-->
            <!--<el-option v-for="item in tplOptions" :key="item.key" :label="item.display_name" :value="item.key" />-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <!--<el-form-item :label="tempDesc.menuUrl" prop="menuUrl">-->
          <!--<el-input v-model="temp.menuUrl" :placeholder="'请输入' + tempDesc.menuUrl" :disabled="!(temp.menuType == '3')"/>-->
        <!--</el-form-item>-->
        <el-form-item :label="tempDesc.tplId" prop="tplId" v-show="temp.menuType == '1'">
          <el-select v-model="temp.tplId" class="filter-item" placeholder="请选择模板" style="width: 280px;" clearable>
            <el-option v-for="item in textTplOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.tplId" prop="tplId" v-show="temp.menuType == '2'">
          <el-select v-model="temp.tplId" class="filter-item" placeholder="请选择模板" style="width: 280px;" clearable>
            <el-option v-for="item in newsTplOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.menuUrl" prop="menuUrl" v-show="temp.menuType == '3' || temp.menuType == '4'">
          <el-input v-model="temp.menuUrl" :placeholder="'请输入' + tempDesc.menuUrl" />
        </el-form-item>
        <el-form-item :label="tempDesc.miniprogramAppid" prop="miniprogramAppid" v-show="temp.menuType == '4'">
          <el-input v-model="temp.miniprogramAppid" :placeholder="'请输入' + tempDesc.miniprogramAppid" />
        </el-form-item>
        <el-form-item :label="tempDesc.miniprogramPagepath" prop="miniprogramPagepath" v-show="temp.menuType == '4'">
          <el-input v-model="temp.miniprogramPagepath" :placeholder="'请输入' + tempDesc.miniprogramPagepath" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {fetchAllAccount} from '@/api/wx-account'
  import {fetchAllTextTpl} from '@/api/wx-text-template'
  import {fetchAllNewsTpl} from '@/api/wx-news-template'
  import {fetchList, createRow, updateRow, deleteRow,listTreeMenu,validateData,syncAccountMenu} from '@/api/wx-menu'
  import waves from '@/directive/waves' // Waves directive
  import treeTable from '@/components/TreeTable'
  //常量title
  const tempDesc = {
    "id":"",
    "parentId":"",
    "menuName":"菜单名称",
    "menuType":"菜单类型",
    "menuLevel":"菜单等级",
    "tplId":"模板名称",
    "menuUrl":"菜单URL",
    "menuSort":"菜单排序",
    "wxAccountId":"公众号名称",
    "miniprogramAppid":"小程序appid",
    "miniprogramPagepath":"小程序页面路径",
    "createTime":"创建时间",
    "updateTime":"更新时间",
    "tplName":"模板名称",
    "wxAccountName":"公众号名称"
  };

  const menuTypeOptions = [
    { key: '1', display_name: '文本消息' },
    { key: '2', display_name: '图文消息' },
    { key: '3', display_name: '网址链接' },
    { key: '4', display_name: '小程序' }
  ];

  const menuLevelOptions = [
    { key: '1', display_name: '一级菜单' },
    { key: '2', display_name: '二级菜单' }
  ];

  export default {
    components: { treeTable },
    directives: {waves},
    data() {
      return {
        tempDesc: tempDesc,
        listLoading: true,
        columns: [
          {
            text: tempDesc.wxAccountName,
            value: 'wxAccountName',
            width: 150
          }
        ],
        data: [
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '增加'
        },
        temp: {
          "id":"",
          "parentId":"",
          "menuName":"",
          "menuType":"",
          "menuLevel":"",
          "tplId":"",
          "menuUrl":"",
          "menuSort":"",
          "wxAccountId":"",
          "miniprogramAppid":"",
          "miniprogramPagepath":"",
          "tplName":"",
          "wxAccountName":""
        },
        accountListOptions:[
        ],
        menuTypeOptions,
        menuLevelOptions,
        tplOptions:[],
        textTplOptions:[],
        newsTplOptions:[],
        rules: {
        },
        accountSelected:"",
        accountNewsTplTemp:{}//每个微信账号对应的图文模板的缓存
      }
    },
    created() {
      this.getList();
      this.getAccountList();
      this.getAllTextTpl();
    },
    methods: {
      getList() {
        this.listLoading = true
        listTreeMenu().then(response => {
          this.data = response.data;
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetTemp() {
        this.temp = {
          "id":"",
          "parentId":"",
          "menuName":"",
          "menuType":"",
          "menuLevel":"",
          "tplId":"",
          "menuUrl":"",
          "menuSort":"",
          "wxAccountId":"",
          "miniprogramAppid":"",
          "miniprogramPagepath":"",
          "tplName":"",
          "wxAccountName":""
        }
      },
      handleCreate(row) {
        this.resetTemp()
        this.dialogStatus = 'create';
        this.dialogFormVisible = true;
        if(!!!row){//一级菜单
          this.temp.menuLevel = "1";//默认一级菜单
        }
        if(!!row){//子菜单
          this.temp.menuLevel = "2";
          this.temp.parentId = row.id;
          this.temp.wxAccountId = row.wxAccountId;
        }

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        if(this.temp.wxAccountId == ''){
          this.$message({ message: '请选择公众号', type: 'warning' });
          return false;
        }
        if(this.temp.menuName == ''){
          this.$message({ message: '请输入菜单名称', type: 'warning' });
          return false;
        }
        if(this.temp.menuType == ''){
          this.$message({ message: '请选择菜单类型', type: 'warning' });
          return false;
        }
        if(this.temp.menuSort == ''){
          this.$message({ message: '请输入菜单排序', type: 'warning' });
          return false;
        }
        if(this.temp.menuType == '1' || this.temp.menuType == '2'){
          if(this.temp.tplId == ''){
            this.$message({ message: '请选择模板', type: 'warning' });
            return false;
          }
        }
        if(this.temp.menuType == '3'){
          if(this.temp.menuUrl == ''){
            this.$message({ message: '请输入'+ tempDesc.menuUrl, type: 'warning' });
            return false;
          }
        }
        if(this.temp.menuType == '4'){
          if(this.temp.menuUrl == ''){
            this.$message({ message: '请输入' + tempDesc.menuUrl, type: 'warning' });
            return false;
          }
          if(this.temp.miniprogramAppid == ''){
            this.$message({ message: '请输入' + tempDesc.miniprogramAppid, type: 'warning' });
            return false;
          }
          if(this.temp.miniprogramPagepath == ''){
            this.$message({ message: '请输入' + tempDesc.miniprogramPagepath, type: 'warning' });
            return false;
          }
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //后台校验数据
            validateData(this.temp).then((res) => {
              var result = res.data;
              if(!result.isCanCreate){
                this.$message({ message: result.msg, type: 'warning' });
                return false;
              }else{

                createRow(this.temp).then(() => {
                  this.getList();
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                });

              }
            });

          }
        })
      },
      handleUpdate(row) {
        //this.temp = Object.assign({}, row) // copy obj
        this.temp.id = row.id;
        this.temp.parentId = row.parentId;
        this.temp.menuName = row.menuName;
        this.temp.menuType = row.menuType;
        this.temp.menuLevel = row.menuLevel;
        this.temp.tplId = row.tplId;
        this.temp.menuUrl = row.menuUrl;
        this.temp.menuSort = row.menuSort;
        this.temp.wxAccountId = row.wxAccountId;
        this.temp.miniprogramAppid = row.miniprogramAppid;
        this.temp.miniprogramPagepath = row.miniprogramPagepath;

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        if(this.temp.wxAccountId == ''){
          this.$message({ message: '请选择公众号', type: 'warning' });
          return false;
        }
        if(this.temp.menuName == ''){
          this.$message({ message: '请输入菜单名称', type: 'warning' });
          return false;
        }
        if(this.temp.menuType == ''){
          this.$message({ message: '请选择菜单类型', type: 'warning' });
          return false;
        }
        if(this.temp.menuSort == ''){
          this.$message({ message: '请输入菜单排序', type: 'warning' });
          return false;
        }
        if(this.temp.menuType == '1' || this.temp.menuType == '2'){
          if(this.temp.tplId == ''){
            this.$message({ message: '请选择模板', type: 'warning' });
            return false;
          }
        }
        if(this.temp.menuType == '3'){
          if(this.temp.menuUrl == ''){
            this.$message({ message: '请输入'+ tempDesc.menuUrl, type: 'warning' });
            return false;
          }
        }
        if(this.temp.menuType == '4'){
          if(this.temp.menuUrl == ''){
            this.$message({ message: '请输入' + tempDesc.menuUrl, type: 'warning' });
            return false;
          }
          if(this.temp.miniprogramAppid == ''){
            this.$message({ message: '请输入' + tempDesc.miniprogramAppid, type: 'warning' });
            return false;
          }
          if(this.temp.miniprogramPagepath == ''){
            this.$message({ message: '请输入' + tempDesc.miniprogramPagepath, type: 'warning' });
            return false;
          }
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateRow(tempData).then(() => {
              this.getList();
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            var params = {"id": row.id};
            deleteRow(params).then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              this.getList();
            });
          });
      },
      formatMenuType(row,column){
        switch (row.menuType) {
          case '1':
              return "文本消息";
              break;
          case '2':
            return "图文消息";
            break;
          case '3':
            return "网址链接";
            break;
          case '4':
            return "小程序";
            break;
        }
      },
      formatMenuLevel(row,column){
        switch (row.menuLevel) {
          case '1':
            return "一级菜单";
            break;
          case '2':
            return "二级菜单";
            break;
        }
      },
      getAccountList(){
        fetchAllAccount().then(response => {
          this.accountListOptions = [];
          for(var i=0;i<response.data.length;i++){
            this.accountListOptions.push({"key":response.data[i].id + '',"display_name":response.data[i].name});
          }
          this.getAllNewsTpl();
        });
      },
      getAllTextTpl(){
        fetchAllTextTpl().then(response => {
          this.textTplOptions = [];
          for(var i=0;i<response.data.length;i++){
            this.textTplOptions.push({"key":response.data[i].id + '',"display_name":response.data[i].tplName});
          }
        });
      },
      getAllNewsTpl(){
        let _this = this;
        for(var j=0;j<_this.accountListOptions.length;j++){
          var _wxAccountId = _this.accountListOptions[j].key;
          var params = {"wxAccountId":_wxAccountId};
          fetchAllNewsTpl(params).then(response => {
//            _this.newsTplOptions = [];
//            for(var i=0;i<response.data.length;i++){
//              _this.newsTplOptions.push({"key":response.data[i].id + '',"display_name":response.data[i].tplName});
//            }
            var _newsTplOptions = [];
            for(var i=0;i<response.data.length;i++){
              _newsTplOptions.push({"key":response.data[i].id + '',"display_name":response.data[i].tplName});
            }
            _this.accountNewsTplTemp[_wxAccountId] = _newsTplOptions;
          });
        }

      },
      onMenuTypeChange(value){
        if(value === ''){
          this.temp.tplId = "";
          this.temp.menuUrl = "";
          this.temp.miniprogramAppid = "";
          this.temp.miniprogramPagepath = "";
        }
        if(value === '1'){
          this.temp.tplId = "";
          this.temp.menuUrl = "";
          this.temp.miniprogramAppid = "";
          this.temp.miniprogramPagepath = "";
          //this.tplOptions = this.textTplOptions;
        }
        if(value === '2'){
          this.temp.tplId = "";
          this.temp.menuUrl = "";
          this.temp.miniprogramAppid = "";
          this.temp.miniprogramPagepath = "";
          //this.tplOptions = this.newsTplOptions;
        }
        if(value === '3'){
          this.temp.tplId = "";
          this.temp.miniprogramAppid = "";
          this.temp.miniprogramPagepath = "";
        }
        if(value === '4'){
          this.temp.tplId = "";
        }
      },
      handlerSyncAccountFans(){
        if(this.accountSelected == ''){
          this.$message({ message: '请选择公众号', type: 'warning' });
          return false;
        }
        this.$confirm('确认需要同步菜单信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var params = {"id":this.accountSelected};
          syncAccountMenu(params).then(response => {
            this.getList();
            this.$notify({
              title: '成功',
              message: '同步菜单成功，请稍后刷新数据查看',
              type: 'success',
              duration: 2000
            })
          });
        });
      }
    },
    watch:{
      'temp.wxAccountId'(newValue, oldValue) {
        this.newsTplOptions = this.accountNewsTplTemp[newValue];
      }
    }

  }
</script>
